import React, { useState } from "react";
import ReactQuill from 'react-quill-new';
import 'react-quill-new/dist/quill.snow.css';
import DisabledContext from "./disabledContext";
import styles from './RichTextField.module.css';

export default function RichTextField({ disabled, value, onChange, ...props }) {
  const context_disabled = React.useContext(DisabledContext);
  disabled = disabled || context_disabled;
  const [, setRefresh] = useState();

  return <ReactQuill className={styles.editor} readOnly={disabled}
    value={value} onChange={(html, delta, source) => {
      if (source === 'user') {
        onChange(html);
      } else {
        setRefresh(true); // 二次刷新，解决表单中初始化后<p>被过滤掉的错误
      }
    }}
    modules={{
      toolbar: [
        [{ 'header': [1, 2, 3, 4, 5, false] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'align': [] }],

        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        ['blockquote', 'code-block'],

        ['clean']
      ],
    }} {...props} />;
}